<template>
  <div class="app-container">
    <div class="app-card">
      <div class="filter-container">
        <el-select v-model="listQuery.status" placeholder="订单状态" clearable style="width: 120px" class="filter-item">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input
          v-model="listQuery.orderNo"
          placeholder="订单编号"
          style="width: 200px;"
          class="filter-item"
          clearable
          @keyup.enter.native="handleFilter"
        />
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          class="filter-item"
          style="width: 300px"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button class="filter-item" icon="el-icon-refresh" @click="resetFilter">
          重置
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="订单编号" align="center" width="350">
          <template slot-scope="scope">
            <span>{{ scope.row.orderNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" width="320">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="350">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">
              {{ scope.row.status | statusTextFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="350">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleDetail(scope.row)">
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 0" 
              type="success" 
              size="mini" 
              @click="handleProcess(scope.row)">
              处理
            </el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              type="warning" 
              size="mini" 
              @click="handleDeliver(scope.row)">
              配送
            </el-button>
            <el-button 
              v-if="scope.row.status === 2" 
              type="success" 
              size="mini" 
              @click="handleComplete(scope.row)">
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 订单详情对话框 -->
      <el-dialog title="订单详情" :visible.sync="dialogVisible" width="50%">
        <div v-loading="detailLoading">
          <el-descriptions title="订单信息" :column="2" border>
            <el-descriptions-item label="订单编号">{{ orderDetail.order ? orderDetail.order.orderNo : '' }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="orderDetail.order ? (orderDetail.order.status | statusFilter) : ''">
                {{ orderDetail.order ? (orderDetail.order.status | statusTextFilter) : '' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="总金额">¥ {{ orderDetail.order ? orderDetail.order.totalAmount : '' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ orderDetail.order ? orderDetail.order.createTime : '' }}</el-descriptions-item>
          </el-descriptions>

          <el-table
            :data="orderDetail.items || []"
            border
            fit
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column label="商品名称" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.productName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单价" align="center" width="120">
              <template slot-scope="scope">
                <span>¥ {{ scope.row.productPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" width="80">
              <template slot-scope="scope">
                <span>{{ scope.row.quantity }}</span>
              </template>
            </el-table-column>
            <el-table-column label="小计" align="center" width="120">
              <template slot-scope="scope">
                <span>¥ {{ scope.row.subtotal }}</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 配送路线信息 -->
          <div v-if="routeInfo && routeInfo.route" style="margin-top: 20px">
            <el-divider content-position="left">配送路线信息</el-divider>
            <el-descriptions title="路线信息" :column="2" border>
              <el-descriptions-item label="路线名称">{{ routeInfo.route.name }}</el-descriptions-item>
              <el-descriptions-item label="路线描述">{{ routeInfo.route.description }}</el-descriptions-item>
            </el-descriptions>
            
            <div class="route-map" v-if="routeInfo.items && routeInfo.items.length > 0">
              <div class="route-map-title">配送路线图</div>
              <div class="route-map-content">
                <div v-for="(item, index) in routeInfo.items" :key="index" class="route-point">
                  <div class="route-step">
                    <div class="point-number" :class="{'current-point': item.leaderId === leaderId}">{{ index + 1 }}</div>
                    <div class="point-line" v-if="index < routeInfo.items.length - 1"></div>
                  </div>
                  <div class="point-card" :class="{'current-point-card': item.leaderId === leaderId}">
                    <div class="point-header">
                      {{ item.leaderName }}
                      <el-tag v-if="item.leaderId === leaderId" size="mini" type="danger">当前位置</el-tag>
                    </div>
                    <div class="point-body">
                      <div class="point-item">
                        <i class="el-icon-phone"></i>
                        <span>{{ item.leaderPhone }}</span>
                      </div>
                      <div class="point-item">
                        <i class="el-icon-location"></i>
                        <span>{{ item.leaderAddress }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="empty-route">
              <i class="el-icon-warning-outline"></i>
              <span>未找到配送路线详情</span>
            </div>
          </div>
          <div v-else-if="orderDetail.order && [1, 2].includes(orderDetail.order.status)" class="empty-route">
            <i class="el-icon-warning-outline"></i>
            <span>您尚未被分配到配送路线，请联系管理员</span>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="viewDeliveryRoute" v-if="routeInfo && routeInfo.route">查看完整路线</el-button>
        </div>
      </el-dialog>

      <!-- 配送路线详情对话框 -->
      <el-dialog title="配送路线详情" :visible.sync="routeDialogVisible" width="70%">
        <div v-loading="routeLoading" class="delivery-route-detail">
          <el-steps :active="currentStepIndex" finish-status="success" align-center v-if="routeInfo && routeInfo.items && routeInfo.items.length > 0">
            <el-step 
              v-for="(item, index) in routeInfo.items" 
              :key="index" 
              :title="item.leaderName"
              :description="item.leaderAddress"
            ></el-step>
          </el-steps>
          
          <el-card class="route-detail-card" shadow="hover" v-if="routeInfo && routeInfo.route">
            <div slot="header" class="clearfix">
              <span>配送路线: {{ routeInfo.route.name }}</span>
            </div>
            <div class="route-description">{{ routeInfo.route.description }}</div>
            
            <el-table :data="routeInfo && routeInfo.items ? routeInfo.items : []" border style="width: 100%; margin-top: 20px">
              <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
              <el-table-column prop="leaderName" label="团长" width="120"></el-table-column>
              <el-table-column prop="leaderPhone" label="联系电话" width="150"></el-table-column>
              <el-table-column prop="leaderAddress" label="配送地址"></el-table-column>
              <el-table-column label="状态" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.leaderId === leaderId" type="danger">当前位置</el-tag>
                  <el-tag v-else-if="getItemIndex(scope.row) < currentStepIndex" type="success">已配送</el-tag>
                  <el-tag v-else-if="getItemIndex(scope.row) > currentStepIndex" type="info">待配送</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          
          <div v-if="!routeInfo || !routeInfo.route" class="empty-route">
            <i class="el-icon-warning-outline"></i>
            <span>未找到配送路线信息</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getLeaderOrders, getOrder, updateOrderStatus } from '@/api/order'
import { getRouteByLeaderId } from '@/api/delivery-route'

export default {
  name: 'LeaderOrder',
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'primary',
        2: 'warning',
        3: 'success',
        4: 'danger'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        0: '待处理',
        1: '已处理',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 10,
        status: null,
        orderNo: null,
        startDate: null,
        endDate: null
      },
      dateRange: [],
      statusOptions: [
        { label: '待处理', value: 0 },
        { label: '已处理', value: 1 },
        { label: '配送中', value: 2 },
        { label: '已完成', value: 3 },
        { label: '已取消', value: 4 }
      ],
      dialogVisible: false,
      detailLoading: false,
      orderDetail: {
        order: null,
        items: []
      },
      leaderId: null,
      routeInfo: {
        route: null,
        items: []
      },
      routeDialogVisible: false,
      routeLoading: false,
      currentStepIndex: 0
    }
  },
  watch: {
    dateRange(val) {
      if (val) {
        this.listQuery.startDate = val[0]
        this.listQuery.endDate = val[1]
      } else {
        this.listQuery.startDate = null
        this.listQuery.endDate = null
      }
    }
  },
  created() {
    this.leaderId = Number(localStorage.getItem('leaderId'))
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      
      // 构建请求参数
      const params = {
        leaderId: this.leaderId,
        status: this.listQuery.status,
        orderNo: this.listQuery.orderNo,
        page: this.listQuery.page - 1, // 后端从0开始计数
        size: this.listQuery.size,
        startDate: this.listQuery.startDate,
        endDate: this.listQuery.endDate
      }
      
      getLeaderOrders(this.leaderId, params).then(response => {
        if (response && response.records) {
          this.list = response.records
          this.total = response.total
        } else if (Array.isArray(response)) {
          this.list = response
          this.total = response.length
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetFilter() {
      this.listQuery.status = null
      this.listQuery.orderNo = null
      this.dateRange = []
      this.listQuery.startDate = null
      this.listQuery.endDate = null
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDetail(row) {
      this.dialogVisible = true
      this.detailLoading = true
      
      // 获取订单详情
      getOrder(row.id).then(response => {
        this.orderDetail = response || { order: null, items: [] }
        
        // 如果订单状态是已处理或配送中，获取配送路线信息
        if (this.orderDetail.order && [1, 2].includes(this.orderDetail.order.status)) {
          this.getDeliveryRouteInfo();
        } else {
          this.routeInfo = {
            route: null,
            items: []
          };
          this.detailLoading = false;
        }
      }).catch(() => {
        this.detailLoading = false
      })
    },
    // 获取配送路线信息
    getDeliveryRouteInfo() {
      getRouteByLeaderId(this.leaderId).then(response => {
        if (response && response.route) {
          this.routeInfo = {
            route: response.route || null,
            items: response.items || []
          };
          
          // 计算当前团长在路线中的位置
          if (this.routeInfo.items && this.routeInfo.items.length > 0) {
            this.currentStepIndex = this.routeInfo.items.findIndex(item => item.leaderId === this.leaderId);
            if (this.currentStepIndex === -1) this.currentStepIndex = 0;
          }
        } else {
          // 如果没有获取到路线信息，设置为默认值
          this.routeInfo = {
            route: null,
            items: []
          };
          this.currentStepIndex = 0;
        }
        
        this.detailLoading = false;
      }).catch(() => {
        // 发生错误时，设置为默认值
        this.routeInfo = {
          route: null,
          items: []
        };
        this.currentStepIndex = 0;
        this.detailLoading = false;
      });
    },
    // 查看完整配送路线
    viewDeliveryRoute() {
      this.routeDialogVisible = true;
      this.routeLoading = false;
    },
    // 获取团长在路线中的索引
    getItemIndex(item) {
      if (!this.routeInfo || !this.routeInfo.items) return -1;
      return this.routeInfo.items.findIndex(i => i.leaderId === item.leaderId);
    },
    // 处理订单
    handleProcess(row) {
      this.$confirm('确认将订单标记为已处理?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 1).then(() => {
          this.$message.success('订单已处理')
          this.getList()
        }).catch(() => {
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    // 配送订单
    handleDeliver(row) {
      this.$confirm('确认将订单标记为配送中?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 2).then(() => {
          this.$message.success('订单已开始配送')
          this.getList()
        }).catch(() => {
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    },
    // 完成订单
    handleComplete(row) {
      this.$confirm('确认将订单标记为已完成?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(row.id, 3).then(() => {
          this.$message.success('订单已完成')
          this.getList()
        }).catch(() => {
          this.$message.error('操作失败')
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.route-map {
  margin-top: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  
  .route-map-title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px;
    border-bottom: 1px solid #EBEEF5;
    background-color: #F5F7FA;
  }
  
  .route-map-content {
    padding: 20px;
    
    .route-point {
      display: flex;
      position: relative;
      
      .route-step {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 40px;
        margin-right: 15px;
        
        .point-number {
          width: 36px;
          height: 36px;
          background-color: #409EFF;
          color: #fff;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          font-weight: bold;
          z-index: 2;
          
          &.current-point {
            background-color: #F56C6C;
            box-shadow: 0 0 10px rgba(245, 108, 108, 0.5);
            transform: scale(1.1);
          }
        }
        
        .point-line {
          width: 2px;
          height: 100%;
          background-color: #409EFF;
          margin-top: 5px;
          margin-bottom: -15px;
          flex-grow: 1;
          position: absolute;
          top: 36px;
          bottom: 0;
          left: 19px;
          z-index: 1;
        }
      }
      
      .point-card {
        flex: 1;
        border: 1px solid #EBEEF5;
        border-radius: 4px;
        margin-bottom: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        
        &.current-point-card {
          border-color: #F56C6C;
          box-shadow: 0 2px 12px 0 rgba(245, 108, 108, 0.2);
        }
        
        .point-header {
          padding: 10px 15px;
          font-weight: bold;
          border-bottom: 1px solid #EBEEF5;
          background-color: #F5F7FA;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        
        .point-body {
          padding: 15px;
          
          .point-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            
            i {
              color: #409EFF;
              margin-right: 10px;
              font-size: 16px;
            }
            
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
      
      &:last-child {
        .point-card {
          margin-bottom: 0;
        }
      }
    }
  }
}

.empty-route {
  margin-top: 20px;
  padding: 30px;
  text-align: center;
  background-color: #F5F7FA;
  border-radius: 4px;
  color: #909399;
  
  i {
    font-size: 30px;
    margin-right: 10px;
    vertical-align: middle;
  }
  
  span {
    font-size: 16px;
    vertical-align: middle;
  }
}

.delivery-route-detail {
  .route-detail-card {
    margin-top: 30px;
    
    .route-description {
      color: #606266;
      margin-bottom: 20px;
    }
  }
}
</style> 